// pages/songDetail/songDetail.js
import request from "../../utils/request";
import PubSub from 'pubsub-js'
import moment from "moment";
const appInstance = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        isPlay:false,
        song:{},
        musicId:'',
        musicLink:'',
        isSlider:false,
        currentTime:'00:00',
        durationTime:'00:00',
        lyric:[],
        lrc:{},
        isPhonograph:true,
        value:0,
        min:0,
        max:0,
        isScroll:false,
        locationIndex:0,
        location:0,
        timeLen:-1,
        locationTime:0,
        locationShowTime:'00:00'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let musicId = options.musicId
        this.setData({
            musicId
        })
        this.getMusicInfo(musicId)

        if(appInstance.globalData.isMusicPlay && appInstance.globalData.musicId===musicId){
            this.setData({
                isPlay:true
            })
        }

        this.backgroundAudioManager = wx.getBackgroundAudioManager()
        this.backgroundAudioManager.onPlay(()=>{
            this.changePlayState(true)
            appInstance.globalData.musicId = musicId
        })
        this.backgroundAudioManager.onPause(()=>{
            this.changePlayState(false)
        })
        this.backgroundAudioManager.onStop(()=>{
            this.changePlayState(false)
        })

        this.backgroundAudioManager.onEnded(()=>{

            PubSub.subscribe('musicId',(_,musicId)=>{

                this.getMusicInfo(musicId)
                this.musicControl(true,musicId)

                PubSub.unsubscribe('musicId')
            })
            PubSub.publish('switchType','next')
            this.setData({
                currentTime:'00:00'
            })
        })

        this.backgroundAudioManager.onTimeUpdate(()=>{
            let currentTime = moment(this.backgroundAudioManager.currentTime * 1000).format('mm:ss')
            this.setData({
                currentTime
            })
            this.update()
        })

        this.getLyric()
    },

    changePlayState(isPlay){
      this.setData({
          isPlay
      });
      appInstance.globalData.isMusicPlay = isPlay
    },

    async getMusicInfo(musicId){
        let musicInfo = await request('/song/detail',{ids:musicId})

        let durationTime = moment(musicInfo.songs[0].dt).format('mm:ss')
        this.setData({
            song:musicInfo.songs[0],
            durationTime
        })
        wx.setNavigationBarTitle({
            title:this.data.song.name
        })
    },

    musicPlay(){
      let isPlay = !this.data.isPlay;
      // this.setData({
      //     isPlay
      // });

      let {musicId,musicLink} = this.data
      this.musicControl(isPlay,musicId,musicLink)
    },

    async musicControl(isPlay,musicId,musicLink){

        if(isPlay){
            if(!musicLink){
                let musicLinkData = await request('/song/url',{id:musicId})
                musicLink = musicLinkData.data[0].url
                this.setData({
                    musicLink
                })
            }
            this.backgroundAudioManager.src = musicLink
            this.backgroundAudioManager.title = this.data.song.name
        }else {
            this.backgroundAudioManager.pause()
        }
    },

    handleSwitch(event){
        let type = event.currentTarget.id

        this.backgroundAudioManager.stop()

        PubSub.subscribe('musicId',(_,musicId)=>{

            this.getMusicInfo(musicId)
            this.musicControl(true,musicId)

            PubSub.unsubscribe('musicId')
        })

        PubSub.publish('switchType',type)
    },

    sliderNow(e){
        let currentTime=moment(e.detail.value*1000).format('mm:ss');
        this.setData({
            currentTime,
            isSlider:true
        });
    },

    slider(e){
        let value=Number(e.detail.value);
        let currentTime=moment(e.detail.value*1000).format('mm:ss');
        this.setData({
            value,
            currentTime,
            isSlider:false
        });
        this.backgroundAudioManager.seek(value);
    },

    scroll(e){
        let i=parseInt(e.detail.scrollTop/27);
        if(!this.data.lyric[i])return;//空白区域，没有时间不执行
        this.setData({
            locationTime:this.data.lyric[i],
            locationShowTime:moment(this.data.lyric[i]*1000).format("mm:ss")
        });

    },

    update(){
        let currentTime = this.backgroundAudioManager.currentTime
        let durationTime = this.backgroundAudioManager.duration
        let value = this.backgroundAudioManager.currentTime
        let max = this.backgroundAudioManager.duration

        if(currentTime&&durationTime) {
            for (let i = 0; i < this.data.lyric.length; i++) {
                if (currentTime > this.data.lyric[this.data.lyric.length - 1]) {//最后的歌词
                    this.setData({
                        location: this.data.lyric.length
                    });
                    break;
                }
                if (currentTime >= this.data.lyric[i] && currentTime < this.data.lyric[i + 1]) {
                    this.setData({
                        location: i
                    });
                    break;
                }
            }

            //设置滚动
            if (this.data.isScroll === false) {
                if (this.data.locationIndex != this.data.location) {
                    this.setData({
                        timeLen: this.data.lyric[this.data.location + 1] - this.data.lyric[this.data.location]
                    });
                }
                this.setData({
                    locationIndex: this.data.location
                });
            }

            durationTime = moment(durationTime * 1000).format('mm:ss')
            currentTime = moment(currentTime * 1000).format('mm:ss')
            this.setData({
                currentTime,
                durationTime,
                max,
                value
            })
        }
    },

    async getLyric(){
      let lyricData = await request('/lyric',{id:this.data.musicId});
      let lyric = lyricData.lrc.lyric
      let lyrArr = [];
      let arr = []
      let pattern = /\[\d{2}:\d{2}.\d{2}|\d{3}\]/g
      let lines = lyric.split(/\n/g);
      lines.map(item=>{
          let i = item.match(pattern)
          if(i){
              i = i[0].replace('[','').replace(']','')
              let time = Number(i.split(':')[0]*60+Number(i.split(':')[1].split('.')[0]))
              lyrArr.push(time)
              arr.push(item.replace(new RegExp("\\[(.*)\\]","g"),""))
          }
      })

      let a1=[],a2=[];
      for(let i=0;i<arr.length;i++){
          if (arr[i] && lyrArr[i]){
              a1.push(arr[i])
              a2.push(lyrArr[i])
          }
      }
      arr=a1,lyrArr=a2

      this.setData({
          lyric:lyrArr,
          lrc:arr
      })
    },

    handleLyric(){
        this.setData({
            isPhonograph:!this.data.isPhonograph
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})